package info.sean.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**   
 * 	验证方法参数是否合法处理类 
 * @author Zhang Xingwang  
 *    
 */
@Component
@Aspect
public class ValidateFiledHandlerAop {

	private static Validator validator;  

	static {  
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();  
		validator = factory.getValidator();  
	}  

	@Pointcut("@annotation(com.ance.consumerfinance.cmc.biz.util.ValidateFiled)")
	private void cut() { }


	/** 
	 * 使用AOP对使用了ValidateFiled的方法进行代理校验 
	 * @throws Throwable  
	 */  
	@Before("cut()")  
	public void validateFiled(JoinPoint  point) throws Throwable  {  
		Object[] args = point.getArgs();
		Set<? extends ConstraintViolation<?>> constraintViolations = validator.validate(args[0]);;
		if (!constraintViolations.isEmpty()) {
			Map<String,StringBuffer> errorMap = new HashMap<String,StringBuffer>(16);
			String property = null;
			for(ConstraintViolation<?> cv : constraintViolations){
				//这里循环获取错误信息，可以自定义格式
				property = cv.getPropertyPath().toString();
				if(errorMap.get(property) != null){
					errorMap.get(property).append("," + cv.getMessage());
				}else{
					StringBuffer sb = new StringBuffer();
					sb.append(cv.getMessage());
					errorMap.put(property, sb);
				}
			}
			//throw new RuntimeException(constraintViolations.iterator().next().getMessage());
			throw new RuntimeException(errorMap.toString());
		}
	}  



}
